'use strict';
var _ = require('lodash');
var User = require('./user.model');
var passport = require('passport');
var config = require('../../config/environment');
var jwt = require('jsonwebtoken');
var validationError = function(res, err) {
	return res.json(422, err);
};

/**
 * Get list of users
 * restriction: 'admin'
 */
exports.index = function(req, res) {
	User.find({}, '-salt -hashedPassword', function(err, users) {
		if (err) return res.send(500, err);
		res.json(200, users);
	});
};

/**
 * Creates a new user
 */
exports.create = function(req, res, next) {
	var newUser = new User(req.body);
	newUser.provider = 'local';
	//newUser.role = 'user';
	if (req.body.setpass) {
		newUser.password = req.body.password;
	}else{
		newUser.password="";
	}
	newUser.save(function(err, user) {
		if (err) return validationError(res, err);
		return res.json(201, user);
	});
}
exports.update = function(req, res, next) {
	//pre, post middleware are not executed on findByIdAndUpdate https://github.com/Automattic/mongoose/issues/964
	//因此会导致code的save前的validate不运行检查code重复
	if (req.body._id) {
		delete req.body._id;
	}
	console.log(req.body);
	User.findById(req.params.id, '-salt -hashedPassword', function(err, user) {
		if (err) {
			return handleError(res, err);
		}
		if (!user) {
			return res.send(404);
		}
		console.log(user);
		var updated = _.assign(user, req.body);
		console.log(updated);
		updated.markModified('courses');
		updated.markModified('klasses');
		//好大的陷阱，反人类设计，mongoose对于Mixed, {}, Array, []无法检查是否更改，因此
		//Any field in your schema with a type of either: Mixed, {}, Array, [] require the use of markModified when its contents are changed
		//http://stackoverflow.com/questions/14922311/mongoose-update-embedded-document-does-not-work
		//http://mongoosejs.com/docs/schematypes.html
		//http://mongoosejs.com/docs/faq.html
		// 3.2.0
		// doc.array.set(3, 'changed');
		// doc.save();
		//
		// // if running a version less than 3.2.0, you must mark the array modified before saving.
		// doc.array[3] = 'changed';
		// doc.markModified('array');
		// doc.save();
		updated.save(function(err,user) {
			if (err) {
				return handleError(res, err);
			}
			console.log("返回",user);
			return res.json(200, user);
		});
	});
};

/**
 * Get a single user
 */
exports.show = function(req, res, next) {
	var userId = req.params.id;
	User.findById(userId, function(err, user) {
		if (err) return next(err);
		if (!user) return res.send(401);
		res.json(user.profile);
	});
};

/**
 * Deletes a user
 * restriction: 'admin'
 */
exports.destroy = function(req, res) {
	User.findByIdAndRemove(req.params.id, function(err, user) {
		if (err) return res.send(500, err);
		return res.send(204);
	});
};

/**
 * Change a users password
 */
exports.changePassword = function(req, res, next) {
	var userId = req.user._id;
	var oldPass = String(req.body.oldPassword);
	var newPass = String(req.body.newPassword);
  console.log(oldPass,newPass);
	User.findById(userId, function(err, user) {
		if (user.authenticate(oldPass)) {
			user.password = newPass;
			user.save(function(err) {
				if (err) return validationError(res, err);
				res.send(200);
			});
		} else {
			res.send(403);
		}
	});
};

/**
 * Get my info
 */
exports.me = function(req, res, next) {
	var userId = req.user._id;
	User.findOne({
		_id: userId
	}, '-salt -hashedPassword', function(err, user) { // don't ever give out the password or salt
		if (err) return next(err);
		if (!user) return res.json(401);
		res.json(user);
	});
};

/**
 * Authentication callback
 */
exports.authCallback = function(req, res, next) {
	res.redirect('/');
};

/**
 * 得到不同角色的用户
 * restriction: 'admin'
 */
exports.teachers = function(req, res) {
	//console.log(req.params.role);
	User.find({
		role: {
			'$in': ['teacher']
		}
	}, '-salt -hashedPassword', function(err, users) {
		//console.log(err,users);
		if (err) return res.send(500, err);
		res.json(200, users);
	});
};

exports.students = function(req, res) {
	//console.log(req.params.klass);
	User.find({
		$query: {
			role: {
				'$in': ['student']
			},
			klass: req.params.klass
		},
		$orderby: {
			code: 1
		}
	}, '-salt -hashedPassword', function(err, users) {
		//console.log(err, users);
		if (err) return res.send(500, err);
		res.json(200, users);
	});
};
function handleError(res, err) {
  return res.send(500, err);
}
